<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">
    <template v-slot:sku_arr="{row}">
      <list :cols="row.config" :data="row.value">
        <template v-slot:action="{row}">
          <el-button v-if="config.type.value!='group'" @click="sku_delete(row)" size="small">删除</el-button>
        </template>
      </list>
      <el-button v-if="config.type.value!='group'" @click="sku_add" size="small">添加自定义规格</el-button>
      <el-button v-if="config.type.value=='table_agent'" @click="select_agent" size="small">选择代理商</el-button>
    </template>
  </forms>
</template>

<script>
export default {
  props: ['__iframe'],
  data(){
    let id = this.$get('id'), btns = undefined;
    let model = {name:this.$get('model_name'), alias:this.$get('model_alias','')};
    if (!id || !model.name) {
      if (this.__iframe){
        iframe.remove('sku_edit');
      }else {
        this.$router.push('index?'+this.param());
      }
    }
    let cols = {
      title: {name:'title', label:'规格标题', type:'text_one', can_edit:true, onchange:this.sku_change},
      link_id: {name:'link_id', label:'关联数据ID', width: '80px'},
      price: {name:'price', label:'价格', type:'text_one',config:'number', can_edit:true, width: '120px', onchange:this.sku_change},
      price_vip: {name:'price_vip', label:'会员价', type:'text_one',config:'number', can_edit:true, width:'120px', onchange:this.sku_change},
      stock: {name:'stock', label:'库存', type:'text_one',config:'number', can_edit:true, width: '120px', onchange:this.sku_change},
      default: {name:'default', label:'默认', type:'radio_switch',config:'', can_edit:true, width: '120px', onchange:this.sku_change},
      action: {name:'action', label:'操作', type:'action',config:'number', width: '60px'},
    }
    let type_map = {default:'自定义规格', group:'规格组合', table_agent:'数据关联：代理商'}
    let forms_config = {
      type: {label:'模式',name:'type',type:'radio',config:type_map,value:'default',tips:''},
      group: {label:'规格组',name:'group',type:'select_more',config:[],tips:'',value:'',onchange:this.group_change, remove: true},
      sku_arr: {label:'参数',name:'sku_arr',type:'sku_arr',config:cols, value:[],tips:''},
    }
    if (!id){
      forms_config.create_time = {label:'创建时间',name:'create_time',tips:''};
    }
    if (this.$get('is_info')){
      s94Mjs.each(forms_config, function (row){ row.is_info = true; });
      btns = [];
    }
    return {
      id: id,
      model: model,
      btns: btns,
      config: forms_config,
      old_sku_arr: [],
      sku_config: {},
      type: 0,
    }
  },
  methods: {
    param(data){
      data = data || {};
      data.model_name = this.model.name;
      data.model_alias = this.model.alias;
      return s94Mjs.param_encode(data);
    },
    onsubmit(formData){
      let url = this.id ? `/admin/${this.model.name}/sku_edit?id=`+this.id : '/admin/_base_/add';
      let post_data = {sku_arr:this.config.sku_arr.value};
      if (this.config.type.value == 'group' ) {
        post_data['sku_config'] = JSON.stringify(Object.assign({},this.sku_config));
      }
      if (/^table_/.test(this.config.type.value)){
        post_data['link_table'] = this.config.type.value.replace('table_','');
      }

      ajax({url:url, method:'POST', data:post_data}, (res)=>{
        if (this.__iframe){
          iframe.exe('edit?'+this.param({id:this.id}), 'get_info');
          iframe.hide('sku_edit');
          if (!this.id) this.$refs['forms'].init();
        }else {
          this.$router.push('index?'+this.param());
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })
    },
    sku_add(){
      let i = this.config.sku_arr.value.length;
      let row = this.old_sku_arr[i] || {title: '', price: '', price_vip: '', stock: 100, link_id:0};
      row.default = 0;
      this.config.sku_arr.value.push(row);
    },
    sku_delete(row){
      let i = this.config.sku_arr.value.indexOf(row);
      this.config.sku_arr.value.splice(i, 1);
    },
    sku_change(row, col, v){
      if (col.name=='default'){
        this.config.sku_arr.value.forEach((row)=>{ row.default = 0; }) //清理默认
      }
      row[col.name] = v;
    },
    group_change(row, v){
      let app = this;
      if (!v) {
        app.sku_config = {};
        app.config.sku_arr.value = [];
        return ;
      }
      let group_config = {};
      let sku_config = {};
      (v ? v.split(',') : []).forEach(function (v){
        let kv = v.split(':');
        if (typeof(group_config[kv[0]]) == 'undefined') group_config[kv[0]]=[];
        group_config[kv[0]].push(kv[1]);
      })
      let sku_list = [{title:[], group_key:[], sku_index:0}];
      let base = 1;
      for (const group in group_config) {
        sku_config[group] = {};
        let old_list = sku_list;
        sku_list = [];
        old_list.forEach(function (old){
          group_config[group].forEach(function (title, j){
            let index = j*base;
            sku_config[group][title] = index;
            sku_list.push({
              title: old.title.concat([group+':'+title]),
              group_key: old.group_key.concat([j]),
              sku_index: old.sku_index + index,
            })
          })
        })
        base *= group_config[group].length;
      }
      app.sku_config = sku_config;

      let old_sku_arr = app.config.sku_arr.value;
      let has_default = false;
      app.config.sku_arr.value = sku_list.map((v,i)=>{
        let row = old_sku_arr[i] || app.old_sku_arr[i] || {price: '', price_vip: '', stock: 100, default:0};
        row.title = v.title.join(' ,');
        row.group_key = v.group_key.join('_');
        row.sku_index = v.sku_index;
        if (has_default){
          row.default = 0;
        }else if(row.default == 1){
          has_default = true;
        }
        return row;
      });
    },
    select_agent(){
      let app = this;
      iframe('/agent/index', {
        btns: {
          '确定_primary'(win_app){
            let selected = win_app.$refs['list_url'].selected;
            let has_ids = app.config.sku_arr.value.map(v=>{ return v.link_id+''; })
            selected.forEach(v=>{
              if (~has_ids.indexOf(v.id+'')) return;
              let row = {price: '', price_vip: '', stock: 100, link_id:v.id, default:0, title:v.title+'(ID='+v.id+')'};
              app.config.sku_arr.value.push(row);
            })
            win_app.__iframe.show = false;
          }
        }
      })
    },
  },
  watch: {
    'config.type.value'(v, oldV){
      if (v == 'group') {
        this.group_change(this.config.group, this.config.group.value);
      }
      this.config.group.remove = v!='group';
      this.config.sku_arr.config.title.can_edit = v!='group';
    }
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;

    ajax({url:'/admin/sku_group/list',cache:true},function(res){
      let config = [];
      s94Mjs.each(res.data.list, function (row, i){
        let child_arr = [];
        row.option.split(',').forEach(function (v, i2){
          let title = row.title+':'+v;
          child_arr.push({
            content: title,
            value: title,
          })
        })
        config.push({
          content: row.title,
          value: '',
          children: child_arr,
        })
      })
      app.config.group.config = config;
      return false
    })
    ajax({url:'/admin/'+this.model.name+'/info?ac=sku&id='+this.id},function (res){
      app.old_sku_arr = [];
      res.data.forEach((v)=>{
        app.old_sku_arr.push({title:v.title, price:v.price, price_vip:v.price_vip, stock:v.stock, default:v.default})
      })
      let forms_init_data = {sku_arr:res.data, type:'default', group:''}
      // 规格类型解析
      if (res.data.length && res.data[0]['sku_config']){
        forms_init_data['type'] = 'group';
        app.sku_config = JSON.parse(res.data[0]['sku_config']);
        let group_arr = [];
        s94Mjs.eachloop(app.sku_config, '', function (row, k, obj, ks){
          if (ks.length==2) group_arr.push(ks.join(':'));
          return true;
        })
        forms_init_data['group'] = group_arr.join(',');
        forms_init_data['group'] = group_arr.join(',');
      }else if (res.data.length && res.data[0]['link_table']){
        forms_init_data['type'] = 'table_'+res.data[0]['link_table'];
      }
      app.$refs['forms'].init(forms_init_data);

      return false
    })

  }
}
</script>
